<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <div><span>药品类别管理</span></div>
        <el-form :inline="true" :model="druglxref" class="demo-form-inline f1">
          <el-form-item label="药品类别编号：">
            <el-input v-model="druglxref.id" placeholder="请输入药品类别编号" />
          </el-form-item>
          <el-form-item label="药品类别名：">
            <el-input v-model="druglxref.name" placeholder="请输入药品类别名" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="finddrug()">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-row class="mb-4">
        <el-button @click="dialogFormVisible1 = true" type="primary" plain>新增药品类别</el-button>
      </el-row>
    </template>

    <el-table ref="multipleTableRef" :data="tableData.slice((currentpage - 1) * pagesize, currentpage * pagesize)"
      style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column property="id" label="药品类别编号" width="150" />
      <el-table-column property="name" label="药品类别名" width="150" />
      <el-table-column property="spci" label="类别说明" width="150" />
      <el-table-column label="操作" width="150">
        <template v-slot="scope">
          <el-button @click="dialogFormVisible2 = true, getdrug(scope.row.id)" size="small">修改</el-button>
          <el-button size="small" type="danger" @click="centerDialogVisible = true,druglxref=scope.row">删除</el-button>
          <el-dialog v-model="centerDialogVisible" title="警告" width="30%" center>
            <span>是否确定删除</span>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="centerDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="centerDialogVisible = false, deletedrug(druglxref)">确认</el-button>
              </span>
            </template>
          </el-dialog>
        </template>
      </el-table-column>
    </el-table>
    <el-row style="margin-top:20px">
      <el-button type="danger" round @click="centerDialogVisible2 = true">批量删除</el-button>
      <el-button @click="toggleSelection()" round>清空选择</el-button>
      <el-pagination class="fy" layout="prev, pager, next" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" :page-size="pagesize" :total="tableData.length">
      </el-pagination>
    </el-row>
  </el-card>
  <el-dialog v-model="dialogFormVisible1" title="新增药品类别" class="wid">
    <el-form :model="druglxref" :rules="rules" ref="ruleFormRef">
      <el-form-item label="药品类别编号" :label-width="formLabelWidth" prop="id">
        <el-input v-model="druglxref.id" />
      </el-form-item>
      <el-form-item label="药品类别名字" :label-width="formLabelWidth" prop="name">
        <el-input v-model="druglxref.name" />
      </el-form-item>
      <el-form-item label="类别说明" :label-width="formLabelWidth" prop="spci">
        <el-select v-model="druglxref.spci" placeholder="请选择类别说明">
          <el-option v-for="(item, index) in lblist" :key="index" :label="item.name" :value="item.name"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible1 = false, cancel()">取消</el-button>
        <el-button type="primary" @click="dialogFormVisible1 = false, addform(ruleFormRef)">确认</el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog v-model="dialogFormVisible2" title="修改药品类别" class="wid">
    <el-form :model="druglxref" :rules="rules" ref="ruleFormRef">
      <el-form-item label="药品类别编号" :label-width="formLabelWidth" prop="id">
        <el-input v-model="druglxref.id" :disabled="true"/>
      </el-form-item>
      <el-form-item label="药品类别名字" :label-width="formLabelWidth" prop="name">
        <el-input v-model="druglxref.name" />
      </el-form-item>
      <el-form-item label="类别说明" :label-width="formLabelWidth" prop="spci">
        <el-select v-model="druglxref.spci" placeholder="请选择类别说明">
           <el-option v-for="(item, index) in lblist" :key="index" :label="item.name" :value="item.name"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible2 = false, cancel()">取消</el-button>
        <el-button type="primary" @click="dialogFormVisible2 = false, updateform(ruleFormRef)">确认</el-button>
      </span>
    </template>
  </el-dialog><el-dialog v-model="centerDialogVisible2" title="警告" width="30%" center>
            <span>是否确定删除</span>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="centerDialogVisible2 = false">取消</el-button>
                <el-button type="primary" @click="centerDialogVisible2 = false, deletedrug2()">确认</el-button>
              </span>
            </template>
          </el-dialog>

</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { ElTable, FormInstance, FormRules } from 'element-plus'
import axios from 'axios';
import { Cons } from './Dept.vue';

export interface Druglx {
  id?: string
  name?: string
  spci?: string
}
onMounted(() => {
  axios.post("/api/bcodename/getcodelist", { codeid: "005" }).then(res => {
    lblist.value = res.data.result;
  })
})
const dialogFormVisible1 = ref(false)
const dialogFormVisible2 = ref(false)
const centerDialogVisible = ref(false)
const centerDialogVisible2 = ref(false)
const formLabelWidth = '140px'
const pagesize = ref(5)
const currentpage = ref(1)
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<Druglx[]>([])
const druglxref = ref<Druglx>({});
const ruleFormRef = ref<FormInstance>()
const tableData = ref<Druglx[]>([])
const lblist=ref<Cons[]>([])
const ids = ref<{
  ids: string[]
}>({ ids: [] })
const rules = ref<FormRules>({
  id: [
    { required: true, message: '请输入药品类型编号', trigger: 'blur' },
  ],
  name: [
    { required: true, message: '请输入药品类型名', trigger: 'blur' },
  ],
  spci: [
    { required: true, message: '请选择详细说明', trigger: 'change' },
  ],
})
const toggleSelection = (rows?: Druglx[]) => {
  if (rows) {
    rows.forEach((row) => {
      multipleTableRef.value!.toggleRowSelection(row, false)
    })
  } else {
    multipleTableRef.value!.clearSelection()
  }
}
const handleSelectionChange = (val: Druglx[]) => {
  ids.value.ids = []
  multipleSelection.value = val
  multipleSelection.value!.forEach((row) => {
    for (let i of ids.value.ids) {
      if (row.id == i) {
        return
      }
    }
    ids.value.ids.push(row.id ?? '')
  })
}
const handleSizeChange = (size) => {

  //一页显示多少条

  pagesize.value = size;

}
const handleCurrentChange = (page) => {

  //页码更改方法

  currentpage.value = page;

}
const addform = async (form) => {
  if (!form) return
  await form.validate((valid) => {
    if (valid) {
      axios.post('/api/drugtype/add', druglxref.value,
        {
          headers: {
            'Authorization': sessionStorage.getItem('authtoken')!
          }
        }).then(
          res => {
            if (res.data.msgId === "A006") {
              alert('添加成功')
              finddrug()
            }
            else {
              alert(res.data.msgId)
            }
          }
        ).catch(error => {
          alert('药品类别编号重复')
        });
    } else {
      alert('表单提交失败！')
      return false
    }
    druglxref.value = {}
  })
}
const updateform = async (form) => {
  if (!form) return
  await form.validate((valid) => {
    if (valid) {
      axios.post('/api/drugtype/update', druglxref.value,
        {
          headers: {
            'Authorization': sessionStorage.getItem('authtoken')!
          }
        }).then(
          res => {
            if (res.data.msgId === "A006") {
              alert('更新成功')
              finddrug()
            }
            else {
              alert(res.data.msgId)
            }
          }
        )
    } else {
      alert('表单提交失败！')
      return false
    }
    druglxref.value = {}
  })
}
const getdrug = (num: string) => {
  for (let i of tableData.value) {
    if (i.id == num) {
      druglxref.value = i
    }
  }
}
const deletedrug = async (row: Druglx) => {
  await axios.post("/api/drugtype/delete", row, {
    headers: {
      'Authorization': sessionStorage.getItem('authtoken')!
    }
  }).then(
    res => {
      if (res.data.msgId === "A006") {
        alert('删除成功')
        finddrug()
        druglxref.value={}
      }
      else {
        alert(res.data.msgId)
      }
    }
  )
}
const deletedrug2 = async () => {
  await axios.post("/api/drugtype/countdelete", ids.value, {
    headers: {
      'Authorization': sessionStorage.getItem('authtoken')!
    }
  }).then(
    res => {
      if (res.data.msgId === "A006") {
        alert('删除成功')
        finddrug()
      }
      else {
        alert(res.data.msgId)
      }
    }
  )
}
const cancel = () => {
  druglxref.value = {}
}
const finddrug = async () => {
  await axios.post("/api/drugtype/find", druglxref.value, {
    headers: {
      'Authorization': sessionStorage.getItem('authtoken')!
    }
  }).then(res => {
    tableData.value = res.data.result
  })
  druglxref.value = {}
}

</script>
<style scoped>
.card-header {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
}

.f1 {
  text-align: left;
}

.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.box-card {
  width: 100%;
}

.el-button--text {
  margin-right: 15px;
}

.el-select {
  width: 220px;
}

.el-input {
  width: 220px;
}

.wid {
  width: 300px;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}

span {
  display: block;
  padding: 10px 0px;
}

.fy {
  text-align: right;
}
</style>